package cn.xyt.dto;

import static java.nio.ByteOrder.LITTLE_ENDIAN;

import cn.tom.kit.IoBuffer;


public class Message {
	public final static byte FLAG = 0x23 & 0xff;
	public final static byte VY = 0x22 & 0xff; //转义 0x23<-->0x22+0x02 || 0x22<-->0x22+0x01
	/*消息头*/
	private Header header;
	/*消息体*/
	private byte[] body;
	/*校验位*/
	private byte check;
	
	public Message() {
	}
	
	public Message(Header header, byte[] body) {
		super();
		this.header = header;
		this.body = body;
	}

	public byte getCheck() {
		return check;
	}
	
	/**
	 * check 位 根据 header + body 的 byte[] 数组1,length 异或 byte[0]^byte[1]...byte[length]
	 * @return
	 */
	public void intCheck(){
		byte[] header = getHeader().toByteBuf();
		byte[] bb = header;
		if(body != null){
			IoBuffer buf = IoBuffer.allocate(header.length +body.length );
			buf.writeBytes(header);
			buf.writeBytes(body);
			bb = buf.array();
		}
		byte check = (byte)0;
		for (int i = 0; i < bb.length; i++) {
			check  = (byte) (check ^ bb[i]);
		}
		this.check = (byte) (check & 0xFF);
	}
	
	public void setCheck(byte check) {
		this.check = check;
	}

	public Header getHeader() {
		return header;
	}

	public void setHeader(Header header) {
		this.header = header;
	}

	public byte[] getBody() {
		return body;
	}

	public void setBody(byte[] body) {
		this.body = body;
	}

	public IoBuffer getBodyBuf() {
		IoBuffer buf = IoBuffer.wrap(body);
		buf.buf().order(LITTLE_ENDIAN);
		return buf;
	}
	
	
}
